import './index.less';
import './Test.ts';
import Food from './Food';
import ScorePanel from './ScorePanel';
import Snake from './Snake';

class GameController {
  food: Food
  scorePanel: ScorePanel
  snake: Snake
  direction: string = ''
  isAlive = true;
  constructor() {
    this.food = new Food()
    this.scorePanel = new ScorePanel()
    this.snake = new Snake()
    document.addEventListener('keydown', this.keydownHandler.bind(this));
  }
  // 键盘事件 确定移动方向
  keydownHandler(event: KeyboardEvent): void {
    this.direction = event.key;
  }
  // 开始运行
  run(): void {
    let X = this.snake.headX;
    let Y = this.snake.headY;
    this.checkEat(X, Y);
    try {
      switch(this.direction){
        case 'ArrowUp':
          Y -= 10;
          this.snake.Y = Y;
          break;
        case 'ArrowDown':
          Y += 10;
          this.snake.Y = Y;
          break;
        case 'ArrowLeft':
          X -= 10;
          this.snake.X = X;
          break;
        case 'ArrowRight':
          X += 10;
          this.snake.X = X;
          break;
      }
    } catch(e) {
      alert((e as any).message + ' GAME OVER ');
      this.isAlive = false;
    }
    // 循环
    this.isAlive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);
  }
  // 是否吃到食物
  checkEat(X: number, Y: number): void {
    if (X === this.food.X && Y === this.food.Y) {
      this.food.generate();
      this.scorePanel.addScore();
      this.snake.addBody();
    }
  }
}

const g = new GameController()
g.run();
